Telegram Group & Telegram Channel
🔍 Как валидировать входные данные

Проверять данные вручную через if-ы — больно, скучно и не масштабируется.
Bean Validation (javax.validation) позволяет валидировать красиво и декларативно, не превращая код в болото.

1️⃣ Добавляем зависимости

implementation("org.springframework.boot:spring-boot-starter-validation")

ИЛИ

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>


2️⃣ Аннотации в DTO
public class UserRequest {

@NotBlank(message = "Имя не должно быть пустым")
private String name;

@Email(message = "Некорректный email")
private String email;

@Min(value = 18, message = "Возраст должен быть 18+")
private int age;

// геттеры и сеттеры
}


3️⃣ Включаем валидацию в контроллере
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest request) {
userService.save(request);
return ResponseEntity.ok().build();
}


Без @Valid перед DTO ничего не сработает.

4️⃣ Глобальный обработчик ошибок
@RestControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationErrors(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.toList();

return ResponseEntity.badRequest().body(errors);
}
}


Теперь ошибки приходят красиво и читаемо в JSON.

5️⃣ Кастомные валидаторы

Если нужно что-то особенное — например, проверка страны:
@Constraint(validatedBy = CountryValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCountry {
String message() default "Страна не поддерживается";
}

public class CountryValidator implements ConstraintValidator<ValidCountry, String> {
private final List<String> allowed = List.of("RU", "US", "DE");

public boolean isValid(String value, ConstraintValidatorContext ctx) {
return allowed.contains(value);
}
}


💬 Всё ещё пишете if (dto.getName() == null)?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6552
Create:
Last Update:

🔍 Как валидировать входные данные

Проверять данные вручную через if-ы — больно, скучно и не масштабируется.
Bean Validation (javax.validation) позволяет валидировать красиво и декларативно, не превращая код в болото.

1️⃣ Добавляем зависимости

implementation("org.springframework.boot:spring-boot-starter-validation")

ИЛИ

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>


2️⃣ Аннотации в DTO
public class UserRequest {

@NotBlank(message = "Имя не должно быть пустым")
private String name;

@Email(message = "Некорректный email")
private String email;

@Min(value = 18, message = "Возраст должен быть 18+")
private int age;

// геттеры и сеттеры
}


3️⃣ Включаем валидацию в контроллере
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest request) {
userService.save(request);
return ResponseEntity.ok().build();
}


Без @Valid перед DTO ничего не сработает.

4️⃣ Глобальный обработчик ошибок
@RestControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationErrors(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.toList();

return ResponseEntity.badRequest().body(errors);
}
}


Теперь ошибки приходят красиво и читаемо в JSON.

5️⃣ Кастомные валидаторы

Если нужно что-то особенное — например, проверка страны:
@Constraint(validatedBy = CountryValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCountry {
String message() default "Страна не поддерживается";
}

public class CountryValidator implements ConstraintValidator<ValidCountry, String> {
private final List<String> allowed = List.of("RU", "US", "DE");

public boolean isValid(String value, ConstraintValidatorContext ctx) {
return allowed.contains(value);
}
}


💬 Всё ещё пишете if (dto.getName() == null)?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6552

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Newly uncovered hack campaign in Telegram

The campaign, which security firm Check Point has named Rampant Kitten, comprises two main components, one for Windows and the other for Android. Rampant Kitten’s objective is to steal Telegram messages, passwords, and two-factor authentication codes sent by SMS and then also take screenshots and record sounds within earshot of an infected phone, the researchers said in a post published on Friday.

Библиотека джависта | Java Spring Maven Hibernate from it


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA